package com.jd.myaaaccount;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode; 
import com.jd.myaaaccount.util.ErrorCode;
import com.jd.myaaaccount.util.OperateCode;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;

public class MapTestActivity extends Activity {
	public LocationClient mLocationClient = null;
	public BDLocationListener myListener = new MyLocationListener();

	Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_map_test);

		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
			}
		};
		mLocationClient = new LocationClient(getApplicationContext());
		mLocationClient.registerLocationListener(myListener);
		initLocation();
		mLocationClient.start();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.map_test, menu);
		return true;
	}

	private void initLocation() {

		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationMode.Hight_Accuracy);
		option.setCoorType("bd09ll");
		int span = 3000;
		option.setScanSpan(span);
		option.setIsNeedAddress(true);
		option.setOpenGps(true);
		option.setLocationNotify(true);
		option.setIsNeedLocationDescribe(true);
		option.setIsNeedLocationPoiList(true);
		option.setIgnoreKillProcess(false);
		option.SetIgnoreCacheException(false);
		option.setEnableSimulateGps(false);
		mLocationClient.setLocOption(option);

	}

	// 最多定位次数
	int locateTime = 3;

	public class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation arg0) {
			locateTime--;
			if (arg0.getLocType() == BDLocation.TypeGpsLocation
					|| arg0.getLocType() == BDLocation.TypeNetWorkLocation) {

				Message msg2 = Message.obtain(handler, OperateCode.LOCATION,
						ErrorCode.SUCCESS, 0, arg0);
				msg2.sendToTarget();
				// mLocationClient.stop();
			} else {
				if (locateTime <= 0) {
					Message msg2 = Message.obtain(handler,
							OperateCode.LOCATION, ErrorCode.FAIL, 0, arg0);
					msg2.sendToTarget();
					// mLocationClient.stop();
				}
			}
		}
	}

}
